package com.cynoware.busappmas.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;

import com.cynoware.busappmas.util.GeneralUtil;
import com.cynoware.busappmas.util.Network;

@SuppressLint("SimpleDateFormat")
public class CheckCameraTime {
	private static CheckCameraTime checkcameratime=new CheckCameraTime();
	private String server="http://192.168.0.149/";
	private String path="web/cgi-bin/hi3510/param.cgi";
	private String getparams="cmd=getservertime&cmd=getntp";
	private String cookie="language=zh-CN;username=YWRtaW4%3D;password=YWRtaW4%3D;authLevel=255";

	
	public static CheckCameraTime instance(){
		return checkcameratime;
	}
	
	public void init(){
		
	}
	
	public void start(){
		new CheckTime().start();
	}

	private class CheckTime extends Thread{
		public void run(){
			while(true){
				if(Network.ishttpConnect(server)){
					String str=Network.httpGet(server, path, getparams, cookie);
					String time=str.substring(str.indexOf("time=")+6,str.indexOf("time=")+20);
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 
					try {
						Date date = df.parse(time);
						long ltime=date.getTime();
						long lnowtime=new Date().getTime();
						if(Math.abs(lnowtime-ltime)>10*60*1000){
							df = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss"); 
							String settime=df.format(new Date());
							String postparams="cmd=setservertime&cururl=http%3A%2F%2F192.168.1.168%2Fweb%2Ftime.html&-time="+settime+"&-timezone=Asia%2FHong_Kong&-dstmode=off&autoupdate=";
							Network.httpPost(server, path, postparams, cookie);
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				GeneralUtil.sleep(10*60*1000);
			}
		}
	}
}
